import { http } from '@/utils/request'
import type { User, CreateUserParams, UpdateUserParams } from '@/types/user'

// 重新导出User类型以供其他模块使用
export type { User, CreateUserParams, UpdateUserParams } from '@/types/user'

// 用户相关API接口

// 获取用户列表
// 定义后端API返回的分页数据结构
interface PaginationResponse<T> {
  items: T[];
  pagination: {
    total: number;
    page: number;
    size: number;
    pages: number;
    has_next: boolean;
    has_prev: boolean;
  };
}

export const getUsers = (params?: {
  search?: string
  page?: number
  size?: number
  username?: string
  email?: string
  role?: string
  status?: string
}) => {
  return http.get<{
    success: boolean;
    data: PaginationResponse<User>;
    message?: string;
  }>('/users', { params }).then(response => {
    // 检查响应结构并正确处理
    if (response.data && response.data.success && response.data.data) {
      const { items, pagination } = response.data.data;
      return {
        items,
        total: pagination.total,
        page: pagination.page,
        size: pagination.size
      };
    }
    // 如果响应已经是期望的格式，直接返回
    if (response.data && 'items' in response.data) {
      return response.data;
    }
    // 默认返回空数据
    return {
      items: [],
      total: 0,
      page: 1,
      size: 20
    };
  });
}

// 获取用户详情
export const getUserById = (id: number) => {
  return http.get<{ success: boolean; data: User; message?: string }>(`/users/${id}`).then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}

// 创建用户
export const createUser = (data: CreateUserParams) => {
  return http.post<{ success: boolean; data: User; message?: string }>('/users', data).then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}

// 更新用户
export const updateUser = (id: number, data: UpdateUserParams) => {
  return http.put<{ success: boolean; data: User; message?: string }>(`/users/${id}`, data).then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}

// 删除用户
export const deleteUser = (id: number) => {
  return http.delete<{ success: boolean; message?: string }>(`/users/${id}`).then(response => {
    if (response.data.success === false) {
      throw new Error(response.data.message || 'Failed to delete user')
    }
    return response.data
  })
}

// 批量删除用户
export const batchDeleteUsers = (ids: number[]) => {
  return http.delete<{ success: boolean; message?: string }>('/users/batch', { data: { ids } }).then(response => {
    if (response.data.success === false) {
      throw new Error(response.data.message || 'Failed to batch delete users')
    }
    return response.data
  })
}

// 重置用户密码
export const resetUserPassword = (id: number, newPassword: string) => {
  return http.post<{ success: boolean; message?: string }>(`/users/${id}/reset-password`, { password: newPassword }).then(response => {
    if (response.data.success === false) {
      throw new Error(response.data.message || 'Failed to reset password')
    }
    return response.data
  })
}

// 获取用户权限
export const getUserPermissions = (id: number) => {
  return http.get<{ success: boolean; data: string[]; message?: string }>(`/users/${id}/permissions`).then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}

// 更新用户权限
export const updateUserPermissions = (id: number, permissions: string[]) => {
  return http.put<{ success: boolean; message?: string }>(`/users/${id}/permissions`, { permissions }).then(response => {
    if (response.data.success === false) {
      throw new Error(response.data.message || 'Failed to update permissions')
    }
    return response.data
  })
}

// 获取用户角色
export const getUserRoles = (id: number) => {
  return http.get<{ success: boolean; data: string[]; message?: string }>(`/users/${id}/roles`).then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}

// 更新用户角色
export const updateUserRoles = (id: number, roles: string[]) => {
  return http.put<{ success: boolean; message?: string }>(`/users/${id}/roles`, { roles }).then(response => {
    if (response.data.success === false) {
      throw new Error(response.data.message || 'Failed to update roles')
    }
    return response.data
  })
}

// 获取当前用户信息
export const getCurrentUser = () => {
  return http.get<{ success: boolean; data: User; message?: string }>('/users/me').then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}

// 更新当前用户信息
export const updateCurrentUser = (data: Partial<UpdateUserParams>) => {
  return http.put<{ success: boolean; data: User; message?: string }>('/users/me', data).then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}

// 修改当前用户密码
export const changePassword = (data: {
  old_password: string
  new_password: string
}) => {
  return http.post<{ success: boolean; message?: string }>('/users/me/change-password', data).then(response => {
    if (response.data.success === false) {
      throw new Error(response.data.message || 'Failed to change password')
    }
    return response.data
  })
}

// 上传用户头像
export const uploadAvatar = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  
  return http.post<{ success: boolean; data: { avatar_url: string }; message?: string }>('/users/me/avatar', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}

// 获取用户统计信息
export const getUserStats = () => {
  return http.get<{
    success: boolean;
    data: {
      total_users: number
      active_users: number
      inactive_users: number
      new_users_this_month: number
      user_growth_rate: number
    };
    message?: string
  }>('/users/stats').then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}

// 导出用户列表
export const exportUsers = (params?: {
  username?: string
  email?: string
  role?: string
  status?: string
}) => {
  return http.get('/users/export', {
    params,
    responseType: 'blob'
  })
}

// 搜索用户
export const searchUsers = (params: { search: string; projectId?: string }) => {
  return http.get<User[]>(`/users/search`, { 
    params: {
      search: params.search,
      exclude_project_id: params.projectId
    }
  }).then(response => {
    return response.data
  })
}

// 导入用户
export const importUsers = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  
  return http.post<{
    success: boolean;
    data: {
      success_count: number
      error_count: number
      errors: string[]
    };
    message?: string
  }>('/users/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => {
    if (response.data.success && response.data.data) {
      return response.data.data
    }
    return response.data
  })
}